#!/usr/bin/perl
# 2013/05/09 Convert to circos format

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [association file] -o [circos assoication data] -n [category number]\n";
}

my %opt;
getopts("i:o:n:", \%opt);
my $FILE_peak_association  = $opt{i};
my $FILE_circos_association = $opt{o};
my $NUMBER_OF_CATEGORY = $opt{n};

#---------------------------------------
# read association
#---------------------------------------
my $TOTAL_NUMBER;
my %association;
my $fh_aso = IO::File->new($FILE_peak_association) or die "cannot open $FILE_peak_association: $!";
while($_ = $fh_aso->getline()){
	s/\r?\n//;
	my ($peak1, $loc1, $peak2, $loc2, $interaction, $pval) = split /\t/;

	if($interaction < 3){
		next;
	}

	my ($chr1, $se1) = split /:/, $loc1;
	my ($start1, $end1) = split /\-/, $se1;
	my ($chr2, $se2) = split /:/, $loc2;
	my ($start2, $end2) = split /\-/, $se2;

	if($chr1 ne 'I' and $chr1 ne 'II' and $chr1 ne 'III'){
		next;
	}
	if($chr2 ne 'I' and $chr2 ne 'II' and $chr2 ne 'III'){
		next;
	}


	# remove telomeric reads
	if($chr1 eq 'I' and $start1 >= 5520001 and $end1 <= 5560000){
		next;
	}
	if($chr2 eq 'I' and $start2 >= 5520001 and $end2 <= 5560000){
		next;
	}
	if($chr1 eq 'II' and $start1 >= 4520001 and $end1 <= 4560000){
		next;
	}
	if($chr2 eq 'II' and $start2 >= 4520001 and $end2 <= 4560000){
		next;
	}

	# remove rDNA reads
	if($chr1 eq 'III' and $start1 >= 2446000){
		next;
	}
	if($chr2 eq 'III' and $start2 >= 2446000){
		next;
	}



	$loc1 = "$chr1 $start1 $end1";
	$loc2 = "$chr2 $start2 $end2";

	$association{"$loc1 $loc2"} = $interaction;
	$TOTAL_NUMBER++;
}
$fh_aso->close();

my $NUMBER_IN_EACH_CATEGORY = $TOTAL_NUMBER / $NUMBER_OF_CATEGORY;
if($NUMBER_OF_CATEGORY != int($NUMBER_IN_EACH_CATEGORY)){
	 $NUMBER_IN_EACH_CATEGORY = int($NUMBER_IN_EACH_CATEGORY) + 1;
}


my $fh_out = IO::File->new($FILE_circos_association, 'w') or die "cannot write $FILE_circos_association: $!";
my $count = 0;
my $current_group = 1;
foreach my $key(sort {$association{$a} <=> $association{$b}} keys %association){
	$count++;
	if($count > $NUMBER_IN_EACH_CATEGORY){
		$count = 0;
		$current_group++;
	}
	$fh_out->print("$key z=$current_group\n");
}
$fh_out->close();

